
import { editProfile,logout,setupUserProfile} from "./auth.js";
window.editProfile = editProfile;
window.logout = logout;
window.setupUserProfile = setupUserProfile;
// 添加加载状态指示
function showLoading() {
    const loader = document.createElement('div');
    loader.id = 'loading-indicator';
    loader.style = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        padding: 20px;
        background: rgba(0,0,0,0.8);
        color: white;
        border-radius: 5px;
    `;
    loader.textContent = '加载中...';
    document.body.appendChild(loader);
}

function hideLoading() {
    const loader = document.getElementById('loading-indicator');
    if (loader) loader.remove();
}


// 新增获取用户信息的函数
async function getUserInfo() {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    await setupUserProfile(username);
    if (!username) {
        showError('URL中缺少username参数');
        console.log('URL中缺少username参数');
        return null;
    }

    try {
        //console.log(`开始获取用户信息，username: ${escapeHTML(username)}`);
        const response = await fetch(`/user-info?username=${escapeHTML(username)}`);
        if (!response.ok) {
            throw new Error(`HTTP错误: ${escapeHTML(response.status)}`);
        }

        const data = await response.json();
        if (data.role !== '教师') {
            showError('当前用户不是教师');
            console.log('当前用户不是教师');
            return null;
        }

        //console.log('成功获取用户信息:', data);
        return data.user_id;
    } catch (error) {
        console.error('获取教师信息失败:', error);
        showError('获取教师信息失败，请稍后重试');
        return null;
    }
}

// 优化后的displayPractices函数
async function displayPractices() {
    showLoading();
    try {
        const teacherId = await getUserInfo();
        if (!teacherId) {
            showError('无法获取教师信息');
            return;
        }

        const practices = await getPractices(teacherId);
        const practiceList = document.getElementById('practiceList');
        practiceList.innerHTML = '';

        if (!practices || practices.length === 0) {
            practiceList.innerHTML = `
                <div class="no-practices">
                    <i class="icon-info"></i>
                    尚未创建任何练习
                </div>
            `;
            return;
        }

        for (const practice of practices) {
            const practiceItem = document.createElement('div');
            practiceItem.className = 'practice-card';

            const questions_response = await fetch(`/api/practice/${escapeHTML(practice.practice_id)}/questions`);
            const { data } = await questions_response.json();
            const totalQuestionCount = data.choice_questions.length + data.fill_questions.length + data.essay_questions.length;
            
            let totalScore = sessionStorage.getItem(`score_${escapeHTML(practice.practice_id)}`);
            if (!totalScore) {
                const scoreRes = await fetch(`/api/practice/${escapeHTML(practice.practice_id)}/total-score`);
                const scoreData = await scoreRes.json();
                totalScore = scoreData.data?.total_score || 0;
                sessionStorage.setItem(`score_${escapeHTML(practice.practice_id)}`, totalScore);
            }

            practiceItem.innerHTML =`<div class="practice-item bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-6 shadow-md transition-all hover:shadow-lg border border-blue-200 hover:border-blue-300">
    <!-- 顶部标题和状态 -->
    <div class="flex items-center justify-between mb-4">
        <div class="flex items-center gap-3">
            <div class="bg-blue-100 p-2 rounded-lg">
                <i class="fa-solid fa-file-pen text-blue-600 text-lg"></i>
            </div>
            <h3 class="text-xl font-bold text-blue-800">${escapeHTML(escapeHTML(practice.practice_name))}</h3>
        </div>
        <span class="text-xs bg-blue-200 text-blue-800 px-3 py-1 rounded-full flex items-center gap-1">
            <i class="fa-solid fa-circle-check text-[8px]"></i>
            已发布
        </span>
    </div>

    <!-- 主要内容区域 -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <!-- 左侧信息 -->
        <div class="col-span-2 space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="flex items-start gap-3">
                    <div class="bg-blue-100 p-2 rounded-lg text-blue-600">
                        <i class="fa-solid fa-book text-sm"></i>
                    </div>
                    <div>
                        <p class="text-sm text-blue-600">所属课程</p>
                        <p class="font-medium text-blue-800">${escapeHTML(practice.course_name)}</p>
                    </div>
                </div>
                
                <div class="flex items-start gap-3">
                    <div class="bg-blue-100 p-2 rounded-lg text-blue-600">
                        <i class="fa-solid fa-clock text-sm"></i>
                    </div>
                    <div>
                        <p class="text-sm text-blue-600">截止时间</p>
                        <p class="font-medium text-blue-800">${escapeHTML(formatDateTime(practice.deadline))}</p>
                    </div>
                </div>
                
                <div class="flex items-start gap-3">
                    <div class="bg-blue-100 p-2 rounded-lg text-blue-600">
                        <i class="fa-solid fa-calendar-plus text-sm"></i>
                    </div>
                    <div>
                        <p class="text-sm text-blue-600">创建时间</p>
                        <p class="font-medium text-blue-800">${escapeHTML(formatDateTime(practice.start_time))}</p>
                    </div>
                </div>
                
                <div class="flex items-start gap-3">
                    <div class="bg-blue-100 p-2 rounded-lg text-blue-600">
                        <i class="fa-solid fa-star text-sm"></i>
                    </div>
                    <div>
                        <p class="text-sm text-blue-600">总分</p>
                        <p class="font-bold text-blue-700">${escapeHTML(totalScore)}分</p>
                    </div>
                </div>
            </div>
            
            <!-- 发布时间 -->
            <div class="flex items-center text-sm text-blue-500 mt-2">
                <i class="fa-solid fa-clock text-blue-400 mr-2"></i>
                <span>发布于 ${escapeHTML(formatLastUpdateTime(practice.start_time))}</span>
            </div>
        </div>
        
        <!-- 右侧操作区 -->
        <div class="flex flex-col justify-between">
            <div class="bg-white rounded-lg p-4 text-center mb-4 shadow-sm border border-blue-100">
                <p class="text-sm text-blue-600">题目总数</p>
                <p class="text-3xl font-bold text-blue-600 mt-1">${escapeHTML(totalQuestionCount)}</p>
            </div>
            
            <div class="flex flex-col gap-3">
                <button id="view-questions-${escapeHTML(practice.practice_id)}" 
                        class="action-btn px-4 py-3 rounded-lg bg-white text-blue-600 font-medium hover:bg-blue-50 transition-colors flex items-center justify-center gap-2 border border-blue-200 hover:border-blue-300">
                    <i class="fa-solid fa-eye text-blue-500"></i>
                    查看题目
                </button>
                <button onclick="removePractice('${escapeHTML(practice.practice_id)}')" 
                        class="action-btn px-4 py-3 rounded-lg bg-white text-red-600 font-medium hover:bg-red-50 transition-colors flex items-center justify-center gap-2 border border-red-200 hover:border-red-300">
                    <i class="fa-solid fa-trash-can text-red-500"></i>
                    删除练习
                </button>
            </div>
        </div>
    </div>
    
    <!-- 题目容器 -->
    <div id="questions-${escapeHTML(practice.practice_id)}" class="questions-container mt-6 pt-6 border-t border-blue-200 space-y-4"></div>
</div>`;
            practiceList.appendChild(practiceItem);

            const viewButton = document.getElementById(`view-questions-${escapeHTML(practice.practice_id)}`);
            const questionsContainer = document.getElementById(`questions-${escapeHTML(practice.practice_id)}`);

            if (viewButton && questionsContainer) {
                viewButton.addEventListener('click', async () => {
                    if (questionsContainer.innerHTML) {
                        questionsContainer.innerHTML = '';
                        viewButton.innerHTML = `<i class="fa-solid fa-eye mr-2"></i>查看题目`;
                        return;
                    }

                    try {
                        const response = await fetch(`/api/practice/${escapeHTML(practice.practice_id)}/questions`);
                        const { data } = await response.json();

                        // 合并所有题目并按顺序排序
                        const allQuestions = [
                            ...(data.choice_questions?.map(q => ({ ...q, type: 'choice' }) || [])),
                            ...(data.fill_questions?.map(q => ({ ...q, type: 'fill' }) || [])),
                            ...(data.essay_questions?.map(q => ({ ...q, type: 'essay' }) || []))
                        ].sort((a, b) => a.question_order - b.question_order);
                        //console.log('获取到的所有题目:', allQuestions);
                        questionsContainer.innerHTML = '';
                        
                        allQuestions.forEach((question, index) => {
                            const questionCard = document.createElement('div');
                            questionCard.className = 'question-card';
                            let content = '';

                            switch(question.type) {
                                case 'choice':
                                    content = `
                                        <div class="question-card bg-white rounded-xl p-6 shadow-md border border-blue-100 mb-6">
                                            <div class="flex justify-between items-center mb-4">
                                                <h4 class="text-lg font-bold text-blue-800">选择题 ${escapeHTML(index + 1)}</h4>
                                                <span class="text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded-full font-medium">客观题</span>
                                            </div>
                                            <div class="form-group mb-4">
                                                <label class="block text-sm font-medium text-blue-600 mb-1">题目内容：</label>
                                                <p class="w-full px-4 py-2 border border-blue-200 rounded-lg bg-blue-50">${escapeHTML(question.question)}</p>
                                            </div>
                                            <div class="options-group grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                                                ${['A','B','C','D'].map((opt, i) => 
                                                    question[`option_${escapeHTML(opt.toLowerCase())}`] ? `
                                                    <div class="form-group">
                                                        <label class="flex items-center text-sm font-medium text-blue-600 mb-1">
                                                            <span class="w-5 inline-block font-bold">${escapeHTML(opt)}</span>
                                                            <span>选项：</span>
                                                        </label>
                                                        <p class="w-full px-4 py-2 border border-blue-200 rounded-lg bg-blue-50">${escapeHTML(question[`option_${escapeHTML(opt.toLowerCase())}`])}</p>
                                                    </div>
                                                    ` : ''
                                                ).join('')}
                                            </div>
                                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                                <div class="form-group">
                                                    <label class="block text-sm font-medium text-blue-600 mb-1">正确答案：</label>
                                                    <p class="w-full px-4 py-2 border border-blue-200 rounded-lg bg-blue-50 font-bold text-blue-700">${escapeHTML(question.correct_answer)}</p>
                                                </div>
                                                <div class="form-group">
                                                    <label class="block text-sm font-medium text-blue-600 mb-1">分值：</label>
                                                    <p class="w-full px-4 py-2 border border-blue-200 rounded-lg bg-blue-50 font-bold text-blue-700">${escapeHTML(question.score)}分</p>
                                                </div>
                                            </div>
                                        </div>
                                    `;
                                    break;
                            
                                case 'fill':
                                    const blanks = [];
                                    for(let i=1; i<=3; i++) {
                                        if(question[`blank${escapeHTML(i)}_answer`]) {
                                            blanks.push({ 
                                                answer: question[`blank${escapeHTML(i)}_answer`],
                                                score: question[`blank${escapeHTML(i)}_score`]
                                            });
                                        }
                                    }
                                    
                                    content = `
                                        <div class="question-card bg-white rounded-xl p-6 shadow-md border border-blue-100 mb-6">
                                            <div class="flex justify-between items-center mb-4">
                                                <h4 class="text-lg font-bold text-blue-800">填空题 ${escapeHTML(index + 1)}</h4>
                                                <span class="text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded-full font-medium">客观题</span>
                                            </div>
                                            <div class="form-group mb-4">
                                                <label class="block text-sm font-medium text-blue-600 mb-1">题目内容：</label>
                                                <p class="w-full px-4 py-2 border border-blue-200 rounded-lg bg-blue-50">${question.question.replace(/__/g, '<span class="underline decoration-blue-300 decoration-2">__</span>')}</p>
                                            </div>
                                            <div class="blank-answers-container space-y-4 mb-4">
                                                ${blanks.map((b, i) => `
                                                    <div class="form-group blank-group grid grid-cols-1 md:grid-cols-2 gap-4">
                                                        <div>
                                                            <label class="block text-sm font-medium text-blue-600 mb-1">空${escapeHTML(i+1)}答案：</label>
                                                            <p class="w-full px-4 py-2 border border-blue-200 rounded-lg bg-blue-50 font-bold text-blue-700">${escapeHTML(b.answer)}</p>
                                                        </div>
                                                        <div>
                                                            <label class="block text-sm font-medium text-blue-600 mb-1">分值：</label>
                                                            <p class="w-full px-4 py-2 border border-blue-200 rounded-lg bg-blue-50 font-bold text-blue-700">${escapeHTML(b.score)}分</p>
                                                        </div>
                                                    </div>
                                                `).join('')}
                                            </div>
                                            <div class="flex gap-2">
                                                <span class="text-sm bg-blue-100 text-blue-700 px-3 py-1 rounded-full font-medium">空白数量：${escapeHTML(blanks.length)}</span>
                                                <span class="text-sm bg-blue-100 text-blue-700 px-3 py-1 rounded-full font-medium">总分值：${escapeHTML(blanks.reduce((sum, b) => sum + b.score, 0))}分</span>
                                            </div>
                                        </div>
                                    `;
                                    break;
                            
                                case 'essay':
                                    content = `
                                        <div class="question-card bg-white rounded-xl p-6 shadow-md border border-blue-100 mb-6">
                                            <div class="flex justify-between items-center mb-4">
                                                <h4 class="text-lg font-bold text-blue-800">解答题 ${escapeHTML(index + 1)}</h4>
                                                <span class="text-xs bg-yellow-100 text-yellow-700 px-2 py-1 rounded-full font-medium">主观题</span>
                                            </div>
                                            <div class="form-group mb-4">
                                                <label class="block text-sm font-medium text-blue-600 mb-1">题目内容：</label>
                                                <p class="w-full px-4 py-2 border border-blue-200 rounded-lg bg-blue-50 min-h-[100px]">${escapeHTML(question.question)}</p>
                                            </div>
                                            <div class="form-group">
                                                <label class="block text-sm font-medium text-blue-600 mb-1">分值：</label>
                                                <p class="w-full px-4 py-2 border border-blue-200 rounded-lg bg-blue-50 font-bold text-blue-700">${escapeHTML(question.score)}分</p>
                                            </div>
                                        </div>
                                    `;
                                    break;
                            }
                            
                            questionCard.innerHTML = content;
                            questionsContainer.appendChild(questionCard);
                        });

                        viewButton.innerHTML = '<i class="icon-list"></i> 收起题目';
                    } catch (error) {
                        questionsContainer.innerHTML = `<p class="error">加载失败：${escapeHTML(error.message)}</p>`;
                    }
                });
            }
        }
    } catch (error) {
        showError(`加载失败：${escapeHTML(error.message)}`);
    } finally {
        hideLoading();
    }
}

// 示例时间格式化方法
function formatLastUpdateTime(timestamp) {
    const now = new Date();
    const updateTime = new Date(timestamp);
    const diffHours = Math.floor((now - updateTime) / 3600000);
    
    if (diffHours < 1) return `${Math.floor(diffHours * 60)}分钟前`;
    if (diffHours < 24) return `${diffHours}小时前`;
    return `${escapeHTML(Math.floor(diffHours / 24))}天前`;
}
// 新增工具函数
function escapeHTML(str) {
    if (typeof str !== 'string') return str;
    return str.replace(/&/g, '&amp;')
              .replace(/</g, '&lt;')
              .replace(/>/g, '&gt;')
              .replace(/"/g, '&quot;')
              .replace(/'/g, '&#039;');
}

function formatDateTime(datetimeStr) {
    try {
        const [datePart, timePart] = datetimeStr.split(' ');
        const [year, month, day] = datePart.split('-');
        return `${year}年${month}月${day}日 ${timePart || ''}`;
    } catch {
        return datetimeStr;
    }
}

// 显示错误信息
function showError(message) {
    const errorContainer = document.getElementById('errorContainer');
    if (!errorContainer) {
        const container = document.createElement('div');
        container.id = 'errorContainer';
        container.className = 'error-message';
        document.body.appendChild(container);
    }
    document.getElementById('errorContainer').textContent = message;
    console.log(`显示错误信息: ${escapeHTML(message)}`);

    // 3秒后自动消失
    setTimeout(() => {
        document.getElementById('errorContainer').textContent = '';
        //console.log(`错误信息消失: ${escapeHTML(message)}`);
    }, 3000);
}

// 初始化加载
window.addEventListener('DOMContentLoaded', () => {
    displayPractices().catch(console.error);
});

// 获取教师创建的练习列表
async function getPractices(teacherId) {
    showLoading();

    try {
        //console.log(`开始获取教师 ${escapeHTML(teacherId)} 的练习列表`);
        // 调用后端API获取练习列表
        const response = await fetch(`/api/get-practices/${escapeHTML(teacherId)}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });

        if (!response.ok) {
            throw new Error(`获取练习列表失败: ${escapeHTML(response.statusText)}`);
        }

        const data = await response.json();
        //console.log('获取到的练习数据:', data); // 打印获取到的数据进行调试
        return data;
    } catch (error) {
        console.error('获取练习列表错误:', error);
        showError(`获取练习列表失败: ${escapeHTML(error.message)}`);
        return [];
    } finally {
        hideLoading();
    }
}

// 移除练习的函数
async function removePractice(practiceId) {
    if (confirm('确定要删除这个练习吗？')) {
        //console.log(`确认删除练习 ${escapeHTML(practiceId)}`);
        try {
            // 显示加载状态
            showLoading();
            // 调用后端 API 删除练习
            const response = await fetch(`/api/practice/${escapeHTML(practiceId)}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error(`删除练习失败: ${escapeHTML(response.statusText)}`);
            }

            // 删除成功后刷新练习列表
            await displayPractices();
            alert('练习删除成功');
        } catch (error) {
            console.error('删除练习时出错:', error);
            showError(`删除练习失败: ${escapeHTML(error.message)}`);
        } finally {
            // 隐藏加载状态
            hideLoading();
        }
    }
}
window.removePractice = removePractice;
document.addEventListener('DOMContentLoaded', function() {
    // 获取"返回"链接元素
    const backLink = document.querySelector('ul.flex li:first-child a');
    if (backLink) {
        // 添加点击事件监听器
        backLink.addEventListener('click', function(event) {
            event.preventDefault(); 
            window.location.href ='practice.html'+window.location.search;
        });
    }
});
function goBack() {
    window.history.back();
}
window.goBack = goBack;

export{
    escapeHTML,
  formatDateTime,
  formatLastUpdateTime,
  showLoading,
  hideLoading,
  showError,
  getUserInfo,
  getPractices,
  displayPractices,
  removePractice,
}